package com.yikaiye.android.yikaiye.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.base.BaseFragment;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.FragmentMineBinding;
import com.yikaiye.android.yikaiye.dialog.CallDialog;
import com.yikaiye.android.yikaiye.model.EventBusModel;
import com.yikaiye.android.yikaiye.model.UserModel;
import com.yikaiye.android.yikaiye.ui.activity.mine.AccountMergeActivity;
import com.yikaiye.android.yikaiye.ui.activity.mine.MessageActivity;
import com.yikaiye.android.yikaiye.ui.activity.mine.MyCompanyActivity;
import com.yikaiye.android.yikaiye.ui.activity.mine.SettingActivity;
import com.yikaiye.android.yikaiye.ui.activity.mine.UserInfoActivity;
import com.yikaiye.android.yikaiye.ui.fragment.viewmodel.MineViewModel;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.UMengUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 我的页面
 */
public class MineFragment extends BaseFragment<FragmentMineBinding, MineViewModel> {
    private CallDialog callDialog;

    @Override
    protected MineViewModel bindModel() {
        return getViewModel(this, MineViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        initDialog();
        viewModel.getUserInfo();
    }

    @Override
    protected void initCtrl() {
        viewModel.userModelMutableLiveData.observe(this, userModel -> {
            if (null != userModel) {
                if (userModel.getMessagCount() > 0) {
                    binding.tvMessageCount.setVisibility(View.VISIBLE);
                    binding.tvMessageCount.setText(String.valueOf(userModel.getMessagCount()));
                } else {
                    binding.tvMessageCount.setVisibility(View.GONE);
                }
                binding.tvUserPhone.setText(userModel.getMobile());
                binding.tvUserName.setText(TextUtils.isEmpty(userModel.getUsername()) ? mContext.getString(R.string.common_user) : userModel.getUsername());
                Glide.with(mContext).load(userModel.getAvatar()).placeholder(R.mipmap.icon_head_def).error(R.mipmap.icon_head_def).into(binding.ivHead);
                UserModel.CustomerModel customerModel = userModel.getCustomer();
                if (customerModel != null) {
                    // auditStatus 审核状态：1：待审核，2：审核通过，3：审核失败
                    binding.ivAuthStatus.setImageResource(customerModel.getAuditStatus() == 2 ? R.mipmap.icon_auth_yes : R.mipmap.icon_mine_no_auth);
                    binding.tvUserName.setText(TextUtils.isEmpty(customerModel.getCustomerName()) ? TextUtils.isEmpty(userModel.getUsername()) ? mContext.getString(R.string.common_user) : userModel.getUsername() : customerModel.getCustomerName());
                    if (!TextUtils.isEmpty(customerModel.getCustomerName())){
                        MyApplication.manager.setRealName(customerModel.getCustomerName());
                    }
                } else {
                    binding.tvUserName.setText(TextUtils.isEmpty(userModel.getUsername()) ? mContext.getString(R.string.common_user) : userModel.getUsername());
                }
                if (userModel.getMergeTels() != null && userModel.getMergeTels().size() > 1) {
                    // 客户有多个联系方式时显示“账号合并”功能
                    binding.rlAccountMerge.setVisibility(View.VISIBLE);
                }
                MyApplication.manager.setCompanyName(userModel.getCompanyName());
            }
            binding.smartRefreshLayout.finishRefresh(500);
        });

        viewModel.mErrorData.observe(this, s -> binding.smartRefreshLayout.finishRefresh(500));
    }

    private void initDialog() {
        callDialog = new CallDialog(getActivity());
    }

    @Override
    protected void initClick() {
        // 个人信息
        viewModel.onDelayClick(binding.llUserInfo, o -> {
            JumpIntent.jump(getActivity(), UserInfoActivity.class);
            UMengUtil.setCountEventId(Constant.MINE_CLICK_USER_INFO);
        });
        // 我的消息
        viewModel.onDelayClick(binding.rlMyMessage, o -> {
            JumpIntent.jump(getActivity(), MessageActivity.class);
            UMengUtil.setCountEventId(Constant.MINE_CLICK_MY_MESSAGE);
        });
        // 我的企业
        viewModel.onDelayClick(binding.rlMyCompany, o -> {
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.TAG_KEY, 1);
            JumpIntent.jump(getActivity(), MyCompanyActivity.class, bundle);
            UMengUtil.setCountEventId(Constant.MINE_CLICK_MY_COMPANY);
        });
        // 账号合并
        viewModel.onDelayClick(binding.rlAccountMerge, o -> JumpIntent.jump(getActivity(), AccountMergeActivity.class));
        // 系统设置
        viewModel.onDelayClick(binding.rlSetting, o -> JumpIntent.jump(getActivity(), SettingActivity.class));
        // 联系我们
        viewModel.onDelayClick(binding.rlContactUs, o -> {
            if (!XXPermissions.isGrantedPermission(mContext, Permission.CALL_PHONE)) {
                XXPermissions.with(this).permission(Permission.CALL_PHONE).request((permissions, all) -> {
                    if (null != callDialog) {
                        callDialog.showDialog();
                    }
                });
            } else {
                if (null != callDialog) {
                    callDialog.showDialog();
                }
            }
        });

//        // 我的发票（暂时不用）
//        viewModel.onDelayClick(binding.rlMyBill, o -> {
//            JumpIntent.jump(getActivity(), MyBillActivity.class);
//            UMengUtil.setCountEventPage(Constant.MINE_CLICK_MY_BILL, mContext.getString(R.string.my_page));
//        });

        binding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> viewModel.getUserInfo());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMessage().equals(Constant.refreshUserInfo)) {
                viewModel.getUserInfo();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
